<template>
  <div class="app-container">
<!--    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">-->
<!--      <el-form-item label="图片地址" prop="bannerPath">-->
<!--        <el-input-->
<!--          v-model="queryParams.bannerPath"-->
<!--          placeholder="请输入图片地址"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item>-->
<!--        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>-->
<!--        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>-->
<!--      </el-form-item>-->
<!--    </el-form>-->

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:banner:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:banner:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:banner:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:banner:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="bannerList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="bannerId" align="center" prop="bannerId" />
      <el-table-column label="图片" align="center" prop="bannerPath" >
        <template slot-scope="scope">
          <el-image
            lazy
            style="width: 100px; height: 100px"
            :preview-src-list="scope.row.bannerPath|getAvatarList"
            :src="scope.row.bannerPath|getAvatar">
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status|statusType">{{scope.row.status|statusText}}</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:banner:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:banner:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改首页横幅对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="状态" prop="status" v-if="!isAdd">
          <el-select v-model="form.status" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="图片地址" prop="bannerPath">
          <el-upload
            ref="upload"
            :limit="1"
            :headers="headerObj"
            class="avatar-uploader"
            :action="imageServer"
            :show-file-list="false"
            accept=".jpg,.png"
            list-type="picture"
            :on-success="handleAvatarSuccess"
            :on-error="handleAvatarError"
            :before-upload="beforeAvatarUpload">
            <img v-if="form.bannerPath" :src="form.bannerPath|getAvatar" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listBanner, getBanner, delBanner, addBanner, updateBanner } from "@/api/system/banner"
import {
  getAvatar,
  getAvatarList,
  getStatus,
  STATUS_OPTIONS,
  IMAGE_UPLOAD,
  getImageServer
} from "../../../utils/jpUtils";
import { getToken } from '../../../utils/auth'
import {Loading} from "element-ui";
export default {
  name: "Banner",
  data() {
    return {
      screenInstance:'',
      options: STATUS_OPTIONS(),
      isAdd:false,
      imageServer:getImageServer(),
      imageUrl: '',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 首页横幅表格数据
      bannerList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        bannerPath: null,
        status: null,
      },
      headerObj: {
        Authorization: 'Bearer '+getToken(),
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        bannerPath: [
          { required: true, message: "图片地址不能为空", trigger: "blur" }
        ],
      }
    }
  },
  created() {
    //因为vue代理了
    //let imageServer = getImageServer()
    //console.log(imageServer)
    //this.imageServer = imageServer;
    this.getList()
  },
  filters: {
    statusText(val){
      //0正常 1停用 2已经使用）
      return getStatus(val).txt
    },
    statusType(val){
      return getStatus(val).type
    },
    getAvatarList,
    getAvatar
  },
  methods: {
    /** 查询首页横幅列表 */
    getList() {
      this.loading = true
      listBanner(this.queryParams).then(response => {
        this.bannerList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    handleAvatarError(res, file) {
      this.closeScreen()
    },
    handleAvatarSuccess(res, file) {
      // "imagePath": "jpsm/static/image/2fc98303b1db4aeb9cbb2a7ae698d4bc.png",
      console.log(res)
      console.log(file)
      this.form.bannerPath = res.data.imagePath
      this.$refs.upload.clearFiles();
      this.closeScreen()
    },
    beforeAvatarUpload(file) {
     // const isJPG = file.type === 'image/jpeg';
      if (file.type !== 'image/jpeg' && file.type !== 'image/png') {
        this.$message.error('必须上传jpeg或者png')
        return false
      }

      const isLt2M = file.size / 1024 / 1024 < 5;

      // if (!isJPG) {
      //   this.$message.error('上传头像图片只能是 JPG 格式!');
      // }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 5MB!');
      }
      this.showScreen('上传图片中...')
      return isLt2M;
    },
    showScreen(txt){
      console.log('scree')
      this.screenInstance = Loading.service({ lock: true,
        text: txt||'loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)' });
    },
    closeScreen(){
      this.$nextTick(() => { // 以服务的方式调用的 Loading 需要异步关闭
        this.screenInstance.close();
      });
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        bannerId: null,
        bannerPath: null,
        status: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.bannerId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加首页横幅"
      this.isAdd=true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.isAdd=false;
      this.reset()
      const bannerId = row.bannerId || this.ids
      getBanner(bannerId).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改首页横幅"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.bannerId != null) {
            updateBanner(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addBanner(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.form.bannerPath = ''
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const bannerIds = row.bannerId || this.ids
      this.$modal.confirm('是否确认删除首页横幅编号为"' + bannerIds + '"的数据项？').then(function() {
        return delBanner(bannerIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/banner/export', {
        ...this.queryParams
      }, `banner_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
